package com.example.administrator.szb.activity;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.bumptech.glide.Glide;
import com.example.administrator.szb.R;
import com.example.administrator.szb.adapter.ProDeatilContentAdapter;
import com.example.administrator.szb.adapter.ProDeatilJGAdapter;
import com.example.administrator.szb.activity.base.BaseActivity;
import com.example.administrator.szb.activity.base.BasePresenter;
import com.example.administrator.szb.activity.base.MVPBaseActivity;
import com.example.administrator.szb.bean.ProjectDetail;
import com.example.administrator.szb.bean.ResultBean;
import com.example.administrator.szb.config.FragmentsFlag;
import com.example.administrator.szb.tinkerutil.SampleApplicationLike;
import com.example.administrator.szb.http.HttpUtil;
import com.example.administrator.szb.http.HttpUtils;
import com.example.administrator.szb.http.OnResultListener;
import com.example.administrator.szb.http.URLAddress;
import com.example.administrator.szb.util.DialogUtil;
import com.example.administrator.szb.util.GetJsonDataUtil;
import com.example.administrator.szb.util.SPUtils;
import com.example.administrator.szb.util.ScreenExpressionUtils;
import com.example.administrator.szb.util.Toasts;
import com.example.administrator.szb.view.MyListView;
import com.example.administrator.szb.xzyw.SuccessActivity;
import com.example.zhouwei.library.CustomPopWindow;
import com.iarcuschin.simpleratingbar.SimpleRatingBar;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ProductDetailActivity extends MVPBaseActivity {

    private LinearLayout activity_product_detail;
    public static boolean canRefresh = false;
    private TextView tv_top_status;
    private LinearLayout jg_ll;
    private LinearLayout look_more_ll;
    private MyListView listView1;
    private LinearLayout status_ll;
    private TextView project_status;
    private MyListView listView2;
    private TextView user_name;
    private TextView user_phone;
    private TextView other_msg,tv_pro_status_title;
    private TextView pro_number;
    private TextView pro_time;
    private LinearLayout footer_ll;
    private TextView tv_jujue;
    private TextView tv_apply,bar_title,bar_right;
    private List<ProjectDetail.YWInfoData> list = new ArrayList<>();
    private List<ProjectDetail.ServiceCounBean> list2 = new ArrayList<>();
    private ProjectDetail projectDetail;
    private ProDeatilJGAdapter adapter2;
    private ProDeatilContentAdapter adapter1;
    private LinearLayout ll_content;
    private ScrollView scrollView2;

    int dd_id;//订单id
    int genre;//1,我申请，2，申请我的
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_product_detail);
        canRefresh = false;
    }

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected void initView() {
        scrollView2 = findViewById(R.id.scrollView2);
        ll_content = findViewById(R.id.ll_content);
        activity_product_detail = (LinearLayout) findViewById(R.id.activity_product_detail);
        tv_top_status = (TextView) findViewById(R.id.tv_top_status);
        jg_ll = (LinearLayout) findViewById(R.id.jg_ll);
        look_more_ll = (LinearLayout) findViewById(R.id.look_more_ll);
        listView1 = (MyListView) findViewById(R.id.listView1);
        status_ll = (LinearLayout) findViewById(R.id.status_ll);
        project_status = (TextView) findViewById(R.id.project_status);
        listView2 = (MyListView) findViewById(R.id.listView2);
        user_name = (TextView) findViewById(R.id.user_name);
        user_phone = (TextView) findViewById(R.id.user_phone);
        other_msg = (TextView) findViewById(R.id.other_msg);
        pro_number = (TextView) findViewById(R.id.pro_number);
        pro_time = (TextView) findViewById(R.id.pro_time);
        footer_ll = (LinearLayout) findViewById(R.id.footer_ll);
        tv_jujue = (TextView) findViewById(R.id.tv_jujue);
        tv_apply = (TextView) findViewById(R.id.tv_apply);
        tv_pro_status_title = findViewById(R.id.tv_pro_status_title);
        bar_title = findViewById(R.id.bar_title);
        bar_title.setText("项目详情");
        bar_right = findViewById(R.id.bar_right);

    }

    @Override
    protected void initEvent() {
        bar_right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (projectDetail.getStatusType()==1){
                    Intent intent = new Intent(context, YJFKActivity.class);
                    intent.putExtra("who", FragmentsFlag.Activity_XMXQ.ordinal());
                    /**
                     * todo id_dd为订单号
                     */
                    intent.putExtra("id_dd",projectDetail.getId());
                    startActivity(intent);
                }else if (projectDetail.getStatusType()==4||projectDetail.getStatusType()==8){
                    //帮我着机构
                    helpFindJG();
                }else if (projectDetail.getStatusType()==6){
                    //选择机构
                    Intent intent = new Intent(context, XZJGActivity.class);
                    intent.putExtra("id_dd", dd_id);
                    startActivity(intent);
                }
            }
        });
        look_more_ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context,FWJGActivity.class);
                intent.putExtra("datas",JSON.toJSONString(projectDetail.getServiceCoun()));
                startActivity(intent);
            }
        });
        listView2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.KITKAT)
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //showpingjia(position);
                int t = list2.get(position).getStatusType();
                if ((t==8||t==9||t==0)&&list2.get(position).getIs_eval()==0){
                    showpingjia(position);
                }

            }
        });
    }

    @Override
    protected void initData() {

        dd_id = getIntent().getIntExtra("dd_id", -1);
        genre = getIntent().getIntExtra("genre",-1);
        adapter2 = new ProDeatilJGAdapter(list2,context);
        listView2.setAdapter(adapter2);
        adapter1 = new ProDeatilContentAdapter(list,context);
        listView1.setAdapter(adapter1);
        requestDeatil();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (canRefresh){
            canRefresh = false;
            requestDeatil();
        }
    }

    private void initViews(){
        if (projectDetail.getStatusType()==1&&genre==1){
            bar_right.setVisibility(View.VISIBLE);
            bar_right.setText("取消订单");
        }else if (projectDetail.getStatusType()==4&&genre==1){
            bar_right.setVisibility(View.VISIBLE);
            bar_right.setText("帮我找机构");
        }else if (projectDetail.getStatusType()==8&&genre==1){
            bar_right.setVisibility(View.VISIBLE);
            bar_right.setText("帮我找机构");
        }else if (projectDetail.getStatusType()==6&&genre==1){
            bar_right.setVisibility(View.VISIBLE);
            bar_right.setText("选择机构");
        }
        else {
            bar_right.setVisibility(View.GONE);
        }
        if (list.size()>0){
            ll_content.setVisibility(View.VISIBLE);
        }
        jg_ll.setVisibility(View.GONE);
        tv_top_status.setText("项目状态："+projectDetail.getStatus());
        tv_pro_status_title.setText(projectDetail.getStatus()+"原因");
        if (projectDetail.getReasons()!=null){
            project_status.setText(projectDetail.getReasons());
        }

        user_name.setText(projectDetail.getName());
        user_phone.setText(projectDetail.getTel());
        other_msg.setText(projectDetail.getContent());
        pro_number.setText(projectDetail.getOrder_number());
        pro_time.setText(projectDetail.getCreate_time());
        status_ll.setVisibility(View.GONE);
        if (projectDetail.getStatusType()==2||/*projectDetail.getStatusType()==4||
                projectDetail.getStatusType()==8||*/projectDetail.getStatusType()==10||
                projectDetail.getStatusType()==0){
            status_ll.setVisibility(View.VISIBLE);
        }
        if (list2!=null&&list2.size()>0){
            adapter2.notifyDataSetChanged();
            jg_ll.setVisibility(View.VISIBLE);
        }
        adapter1.notifyDataSetChanged();
        scrollView2.smoothScrollTo(0,0);
    }

    private void requestDeatil(){
        Map<String,Object> params = new HashMap<>();
        params.put("users_id", SPUtils.getUserId());
        params.put("genre",genre);
        params.put("indent_id",dd_id);
        params.put("code", HttpUtil.getParam());
        HttpUtils.post(activity,URLAddress.URLBASE+URLAddress.URL_DDXQ, params,  new OnResultListener() {
            @Override
            public void onSuccess(int requestCode, String str) {

                try {
                    projectDetail = JSON.parseObject(str,new TypeReference<ProjectDetail>(){});
                } catch (Exception e) {

                    str = str.replace("\"indentInfo\":[]","\"indentInfo\":null");
                    projectDetail = JSON.parseObject(str,new TypeReference<ProjectDetail>(){});
                }

                list2.clear();

                if (projectDetail.getServiceCoun()==null)
                {
                    projectDetail.setServiceCoun(new ArrayList<ProjectDetail.ServiceCounBean>());
                }
                list2.addAll(projectDetail.getServiceCoun());
                list.clear();
                ProjectDetail.YWInfoData infoData = new ProjectDetail.YWInfoData();
                infoData.setKeyName("业务类型");
                infoData.setValueName(projectDetail.getBusinessName());
                list.add(infoData);
                if(projectDetail.getIndentInfo()!=null){

                    for (Map.Entry<Integer, ProjectDetail.YWInfoData> entry : projectDetail.getIndentInfo().entrySet()) {
                        //Map.entry<Integer,String> 映射项（键-值对）  有几个方法：用上面的名字entry
                        //entry.getKey() ;entry.getValue(); entry.setValue();
                        //map.entrySet()  返回此映射中包含的映射关系的 Set视图。
                        list.add(entry.getValue());
                    }

                }
                initViews();
            }

            @Override
            public void onFailure(int requestCode, String str) {

            }
        });
    }

    /**
     * 帮我炸机构
     */
    private void helpFindJG() {
        DialogUtil.showProgressbar(this,R.layout.xmxq_my_activity);
        HashMap<String,String> map = new HashMap<>();
        map.put("code",HttpUtil.getParam());
        map.put("indent_id",dd_id+"");
        String json = GetJsonDataUtil.simpleMapToJsonStr(map);
        String url = URLAddress.URLBASE + URLAddress.URL_FPJG;
        HttpUtil.RequestGsonPost(SampleApplicationLike.getQueueInstance(), Request.Method.POST, ResultBean.class, url, map, new Response.Listener() {
            @Override
            public void onResponse(Object response) {
                ResultBean resultBean = (ResultBean) response;
                if (resultBean.getResult() == 1){
                    DialogUtil.loading.dissmiss();
                    startActivity(new Intent(context,SuccessActivity.class));

                }else{
                    DialogUtil.loading.dissmiss();
                    Toasts.show(context, ""+resultBean.getErr_msg(), Toast.LENGTH_SHORT);
                }
                DialogUtil.loading.dissmiss();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                DialogUtil.loading.dissmiss();
            }
        });
    }
    /**
     * 初始化popupwindow弹出框
     */
    CustomPopWindow popWindow;
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    public void showPopupwindow(int view_layout_id, int width, int height, int rootview_layout_id, BaseActivity.CallbackPopuwindow callback) {
        View popwindow_view = LayoutInflater.from(this).inflate(view_layout_id, null);
        View rootview = LayoutInflater.from(this).inflate(rootview_layout_id, null);
        //处理popWindow 显示内容
        callback.doSomeThing(popwindow_view);
        if (view_layout_id != R.layout.view_progressbar) {
            popWindow = new CustomPopWindow.PopupWindowBuilder(this)
                    .setView(popwindow_view)//显示的布局，还可以通过设置一个View
                    .enableBackgroundDark(true) //弹出popWindow时，背景是否变暗
                    .setBgDarkAlpha(0.7f) // 控制亮度
                    .size(width, height) //设置显示的大小，不设置就默认包裹内容
                    .setFocusable(true)//是否获取焦点，默认为ture
                    .setOutsideTouchable(true)//是否PopupWindow 以外触摸dissmiss
                    .create()//创建PopupWindow
                    .showAtLocation(rootview, Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL, 0, 0);
        }
    }
    
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    public void showpingjia(final int pos){
        showPopupwindow(R.layout.view_popupwindow_pj, ScreenExpressionUtils.dip2px(context,335), ScreenExpressionUtils.dip2px(context,276), R.layout.activity_product_detail, new BaseActivity.CallbackPopuwindow() {

            @Override
            public void doSomeThing(final View view) {

                ((TextView)view.findViewById(R.id.textView158)).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Toasts.show(context, "this is ", Toast.LENGTH_SHORT);
                        popWindow.dissmiss();
                    }
                });
                //imageView50
                Glide.with(context).load(list2.get(pos).getZhenshi_img()).error(R.drawable.mrtx).into(((ImageView) view.findViewById(R.id.imageView50)));
                ((TextView)view.findViewById(R.id.textView156)).setText(list2.get(pos).getName());
                (view.findViewById(R.id.textView159)).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view_) {
                        int scroe = (int) ((SimpleRatingBar)view.findViewById(R.id.star_scroe)).getRating();
                        requestPjData(list2.get(pos).getUsers_id(),scroe*2);
                        popWindow.dissmiss();
                    }
                });

            }
        });
    }
    /**
     * 评分
     * @param right_users_id
     * @param scroe
     */
    private void requestPjData(int right_users_id, int scroe) {
        HashMap<String,String> map = new HashMap<>();
        map.put("code",HttpUtil.getParam());
        map.put("users_id",SampleApplicationLike.getUserloginInstance().getId()+"");
        map.put("indent_id",dd_id+"");
        map.put("right_users_id",right_users_id+"");
        map.put("score",scroe+"");
        String json = GetJsonDataUtil.simpleMapToJsonStr(map);
        String url = URLAddress.URLBASE + URLAddress.URL_PJ;
        HttpUtil.RequestGsonPost(SampleApplicationLike.getQueueInstance(), Request.Method.POST, ResultBean.class, url, map, new Response.Listener() {
            @Override
            public void onResponse(Object response) {
                ResultBean b = (ResultBean) response;
                if (b.getResult() == 1){
                    Toasts.show(context, "评价成功", Toast.LENGTH_SHORT);
                    requestDeatil();
                }else{
                    Toasts.show(context, ""+b.getErr_msg(), Toast.LENGTH_SHORT);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
    }

}
